/*
 * @Author: Marte
 * @Date:   2016-10-25 15:50:45
 * @Last Modified by:   Marte
 * @Last Modified time: 2016-10-28 17:47:24
 */

'use strict';

var sequelizeService = require('../utils/sequelizeService');

var Pic = sequelizeService.models.Pic;
var Type = sequelizeService.models.Type;
var Remark = sequelizeService.models.Remark;
var TypeRemark = sequelizeService.models.TypeRemark;
var RemarkGroup = sequelizeService.models.RemarkGroup;
var PicTypeRemarkGroup = sequelizeService.models.PicTypeRemarkGroup;

var _ = require('underscore');
var Promise = require('bluebird');

var controller = {

};

/**
 * [getJsonByTypeRemark 根据指定证件类型和评语获取图片]
 * @param  {[type]}   req  [description]
 * @param  {[type]}   res  [description]
 * @param  {Function} next [description]
 * @return {[type]}        [Json]
 */
controller.getJsonByTypeRemark = function(req, res, next) {
    var typeId = req.query.typeid;
    var remarkId = req.query.remarkid;
    var getPics = PicTypeRemarkGroup.findJsonByTypeAndRemark(typeId, remarkId);

    getPics
        .then(function(pics) {
            return res.status(200).json(pics);
        })
        .error(function(err) {
            return res.status(400).json({
                error: '读取数据出错！',
                syserror: err.message
            });
        })
        .catch(function(err) {
            return res.status(500).json({
                error: '读取数据出错！',
                syserror: err.message
            });
        });
};

/**
 * [getJsonByTypeRemark 根据指定证件类型和评语获取图片并按评语组分组]
 * @param  {[type]}   req  [description]
 * @param  {[type]}   res  [description]
 * @param  {Function} next [description]
 * @return {[type]}        [Json]
 */
controller.getAndGroupByGroupNameByTypeRemark = function(req, res, next) {
    var typeId = req.query.typeid;
    var remarkId = req.query.remarkid;
    var getPics = PicTypeRemarkGroup.findJsonByTypeAndRemark(typeId, remarkId);

    getPics
        .then(function(pics) {
            //获取到数据后，将数据按RemarkGroupId分组
            var picsByGroup = {};
            _.each(pics, function(item, i) {
                if (!picsByGroup[item.RemarkGroup.groupName]) {
                    picsByGroup[item.RemarkGroup.groupName] = [
                        item
                    ];
                } else {
                    picsByGroup[item.RemarkGroup.groupName].push(item);
                }
            });

            //console.log(picsByGroup);
            return res.status(200).json(picsByGroup);
        })
        .error(function(err) {
            return res.status(400).json({
                error: '读取数据出错！',
                syserror: err.message
            });
        })
        .catch(function(err) {
            return res.status(500).json({
                error: '读取数据出错！',
                syserror: err.message
            });
        });
};

/**
 * [postInputDataToJson 提交相片类型评语分组并保存到服务器]
 * @param  {[type]}   req  [description]
 * @param  {[type]}   res  [description]
 * @param  {Function} next [description]
 * @return {[type]}        [description]
 */
controller.postInputDataToJson = function(req, res, next) {
    var inputObj = req.body.input;
    //console.log(inputObj);

    if (inputObj.remark && inputObj.typeName && inputObj.picGroup.length > 0) {
        var setTypeRemark = [];
        var setBefore = [];

        var hasValidGroup = false;
        //先判断是否存在有效分组
        _.each(inputObj.picGroup, function(picGroup, i) {
            if (picGroup.pic.length > 1) {
                hasValidGroup = true;
                return;
            }
        });
        console.log('hasValidGroup ');
        console.log(hasValidGroup);
        if (hasValidGroup) {
            //证件类型不存在则保存，更新类型ID
            setTypeRemark.push(Type.findOrCreate({
                where: {
                    typeName: inputObj.typeName
                },
                defaults: {
                    typeName: inputObj.typeName
                }
            }).spread(function(_type) {
                inputObj.typeId = _type.id;
            }));

            setTypeRemark.push(Remark.findOrCreate({
                where: {
                    remark: inputObj.remark
                },
                defaults: {
                    remark: inputObj.remark
                }
            }).spread(function(_remark) {
                inputObj.remarkId = _remark.id;
            }));

            Promise.all(setTypeRemark)
                .then(function() {
                    //证件类型和评语关系表不存在则保存
                    setBefore.push(TypeRemark.findOrCreate({
                        where: {
                            RemarkId: inputObj.remarkId,
                            TypeId: inputObj.typeId
                        },
                        defaults: {
                            RemarkId: inputObj.remarkid,
                            TypeId: inputObj.typeId
                        }
                    }));

                    _.each(inputObj.picGroup, function(picGroup, i) {
                        //该分组的图片项是否大于1
                        if (picGroup.pic.length > 1) {
                            //分组+评语不存在则保存,并更新分组ID
                            setBefore.push(RemarkGroup.findOrCreate({
                                    where: {
                                        RemarkId: inputObj.remarkId,
                                        groupName: picGroup.groupName
                                    },
                                    defaults: {
                                        RemarkId: inputObj.remarkId,
                                        groupName: picGroup.groupName
                                    }
                                })
                                .spread(function(_group) {
                                    picGroup.id = _group.id;
                                })
                            );
                        }
                    });
                    return Promise.all(setBefore);
                })
                .then(function() {
                    var setInput = [];
                    _.each(inputObj.picGroup, function(picGroup) {
                        //该分组的图片项是否大于1
                        if (picGroup.pic.length > 1) {
                            _.each(picGroup.pic, function(pic) {
                                if (pic.id) {
                                    setInput.push(Pic.findById(pic.id)
                                        .then(function(_pic) {
                                            //console.log(pic);
                                            return _pic.update({
                                                fileName: pic.fileName
                                            });
                                        }));
                                    setInput.push(PicTypeRemarkGroup.findOrCreate({
                                        where: {
                                            RemarkId: inputObj.remarkId,
                                            TypeId: inputObj.typeId,
                                            RemarkGroupId: picGroup.id,
                                            PicId: pic.id
                                        },
                                        defaults: {
                                            RemarkId: inputObj.remarkId,
                                            TypeId: inputObj.typeId,
                                            RemarkGroupId: picGroup.id,
                                            PicId: pic.id
                                        }
                                    }));
                                }
                            });
                        }
                    });
                    return Promise.all(setInput);
                })
                .then(function() {
                    res.json({ success: 'ok' });
                })
                .error(function(err) {
                    return res.status(400).json({
                        error: '保存失败.',
                        syserror: err.message
                    });
                });
        } else {
            console.log('没有有效的分组图片信息');
            return res.status(400).json({
                error: '没有有效的分组相片信息.',
                syserror: '没有有效的分组相片信息.'
            });
        }

    }

};

controller.registerPath = function(router) {

    /*根据证件类型和评语获取图片并按评语组别分组*/
    router.addPathGetHanlder('/api/picTypeRemarkGroups/groupbygroupname', controller.getAndGroupByGroupNameByTypeRemark);

    /*根据证件类型和评语获取图片*/
    router.addPathGetHanlder('/api/picTypeRemarkGroups', controller.getJsonByTypeRemark);

    /*保存证件类型、评语、图片分组*/
    router.addPathPostHanlder('/pictyperemarkgroups', controller.postInputDataToJson);
};

module.exports = controller;
